import React, { Component } from 'react'
import classnames from 'classnames'
const Styles = require('./index.less')
export default class Tabs extends Component {
  static TabPane(props) {
    return (
      props.children
    )
  }
  constructor(props) {
    super(props)
    this.title = React.Children.map(props.children, v => v.props.tab)
    this.tabs = null
    this.tabContent = []
    this.tabContentTop = []
    this.tabsHeight = 0
    this.setTabsRef = (ele) => {this.tabs = ele} 
    this.setContentRef = (index) => (ele) => {this.tabContent[index] = ele}
    this.html = document.documentElement
    this.state = {
      currentIndex: -1,
      tabsFixed: false
    }
    this.tabClick = this.tabClick.bind(this)
  }
  componentDidUpdate(prevProps, prevState) {
    const newIndex = this.state.currentIndex
    const prevIndex = prevState.currentIndex
    if (newIndex !== prevIndex) {
      if (newIndex !== -1) this.html.scrollTop = this.tabContentTop[newIndex] - this.tabsHeight
    }
  }
  tabClick(index) {
    return () => {
      this.setState({
        currentIndex: index
      })
    }
  }
  componentDidMount() {
    this.tabContentTop = this.tabContent.map((ele) => ele.getBoundingClientRect().top + this.html.scrollTop)
    let tabsTop = this.tabs.getBoundingClientRect().top + this.html.scrollTop
    this.tabsHeight = this.tabs.getBoundingClientRect().height
    this.scrollToTabsFixed = () => {
      let scrollTop = this.html.scrollTop
      const { tabsFixed } = this.state
      let tabsShouldFixed = scrollTop > tabsTop
      if (tabsShouldFixed!==tabsFixed) {
        this.setState({
          tabsFixed: tabsShouldFixed
        })
      }
    }
    window.addEventListener('scroll', this.scrollToTabsFixed)
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.scrollToTabsFixed)
  }
  render() {
    const { children } = this.props
    const { currentIndex, tabsFixed } = this.state
    return (
      <div className={Styles.tabsModule}>
        <div className={classnames({
          [Styles.tabs]: true,
          [Styles.fixed]: tabsFixed})} ref={this.setTabsRef}>
          <div className={Styles.container}>
            {
              this.title.map((item, index) => (
                <div className={classnames({
                  [Styles.tab]: true,
                  [Styles.active]: currentIndex === index
                })} key={item}
                    onClick={this.tabClick(index)}>
                  <span>{item}</span>
                </div>
              ))
            }
          </div>
        </div>
        <div className={classnames({[Styles.tabsContent]: true, [Styles.fixed]: tabsFixed})}>
          {
            React.Children.map(children, (item, index) => (
              <div key={item} className={Styles.tabContent} ref={this.setContentRef(index)}>{item}</div>
            ))
          }
        </div>
      </div>
    )
  }
}